package com.yuanhua.xcxmng.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.yuanhua.xcxmng.wechat.cache.LocalCache;
import com.yuanhua.xcxmng.wechat.entity.*;
import com.yuanhua.xcxmng.wechat.service.MyService;
import com.yuanhua.xcxmng.wechat.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wechat/step")
public class StepController extends BaseController {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private MyService   myService;

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("userStepsInfo")
    public String userStepsInfo(String threeSession) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];

        try {
            UserTarget userTarget = myService.findTargetByOpenId(openId);
            User user = myService.findUserByOpenId(openId);
            UserStepInfo userStepInfo = new UserStepInfo();
            userStepInfo.setNo(user.getNo());
            userStepInfo.setPreNo(user.getPreNo());
            userStepInfo.setUpNo((user.getNo() != 0 && user.getPreNo() != 0) ? user.getNo() - user.getPreNo() : 0);
            List<UserRun> userRunsWeek = myService.findRunDataByOpenIdDate(openId, DateUtil.beginOfWeek(new Date()), DateUtil.endOfWeek(new Date()));
            List<UserRun> userRunsMonth = myService.findRunDataByOpenIdDate(openId, DateUtil.beginOfMonth(new Date()), DateUtil.endOfMonth(new Date()));
            int weekStep = 0;
            int monthStep = 0;
            int weekYes = 0;
            int monthYes = 0;
            if (CollectionUtil.isNotEmpty(userRunsWeek)) {
                for (UserRun run : userRunsWeek) {
                    weekStep += run.getStep();
                    if (run.getTargetyes() == 1) {
                        weekYes++;
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(userRunsMonth)) {
                for (UserRun run : userRunsMonth) {
                    monthStep += run.getStep();
                    if (run.getTargetyes() == 1) {
                        monthYes++;
                    }
                }
            }
            userStepInfo.setWeekStep(weekStep);
            userStepInfo.setWeekYes(weekYes);
            userStepInfo.setMonthStep(monthStep);
            userStepInfo.setMonthYes(monthYes);
            return JsonUtils.toJson(userStepInfo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "fail";
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("orderStep")
    public String orderStep(String threeSession, Integer next) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];

        try {
            if (next == null || next < 0) {
                next = 0;
            }

            Page<User> pageUser = PageHelper.offsetPage(next, 10, true);
            List<User> users = myService.orderByNo();
            users.stream().forEach(x -> {
                if (x.getOpenId().equals(openId)) {
                    x.setIsSelf(1);
                }
            });
            if (next == 0) {
                //第一次查
                //要把本人放第一个
                User user = myService.findUserByOpenId(openId);
                user.setIsSelf(1);
                users.add(0, user);
            }
            if (next >= pageUser.getTotal()) {
                return JsonUtils.toJson(Lists.newArrayList());
            }

            return JsonUtils.toJson(users);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return "fail";
        } finally {
            PageHelper.clearPage();
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("exchangeCurreny")
    public String exchangeCurreny(String threeSession) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        int hh = DateUtil.thisHour(true);
        int mm = DateUtil.thisMinute();
        int alllMinutes = hh*60+mm;
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }

        if ((alllMinutes > 22*60+30 && alllMinutes < 24*60)) {
            return "notime";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];

        try {
            UserRun userRun = myService.findRunDataByOpenIdDate(openId, DateUtil.beginOfDay(new Date()));
            User user = myService.findUserByOpenId(openId);
            Long step = userRun.getStep();
            if (step == null || step < 5000) {
                return "不满5000步，无法兑换";
            }
            Long currency = step / 5000;
            if (currency > 6) {
                currency = 6L;
            }
            userRun.setCurrency(currency);
            myService.updateUserRun(userRun);
            Long userCurrentcy = user.getCurrency() == null ? 0L : user.getCurrency();
            user.setCurrency(userCurrentcy + currency);
            myService.updateUser(user);
            return "兑换 " + currency + " 运动币成功";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "fail";
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("todayRun")
    public String todayRun(String threeSession) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String sessionKey = StringUtils.split(sessionCode, "^#^")[0];
        String openId = StringUtils.split(sessionCode, "^#^")[1];

        try {
            UserRun userRun = myService.findRunDataByOpenIdDate(openId, DateUtil.beginOfDay(new Date()));
            return JsonUtils.toJson(userRun);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "fail";
        }
    }

    public static void main(String[] args) {
        int hh = DateUtil.thisHour(true);
        int mm = DateUtil.thisMinute();
        int hhmm = Integer.valueOf(hh + "" + mm);
        System.out.println(hhmm < 2230);
    }
}
